package cn.wjx.taobaounion.utils;

import android.content.Context;
import android.content.SharedPreferences;

import com.google.gson.Gson;

import cn.wjx.taobaounion.base.BaseApplication;
import cn.wjx.taobaounion.model.domain.CacheWithDuration;

/**
 * @author WuChangJian
 * @date 2020/6/27 8:12
 */
public class JsonCacheUtil {
    private static final String JSON_CACHE_SP_NAME = "json_cache_sp_name";
    private static JsonCacheUtil sJsonCacheUtil;
    private Gson mGson;
    private SharedPreferences mSharedPreferences;

    private JsonCacheUtil() {
        mGson = new Gson();
        mSharedPreferences = BaseApplication.getAppContext().getSharedPreferences(JSON_CACHE_SP_NAME, Context.MODE_PRIVATE);
    }

    public void saveCache(String key, Object value) {
        this.saveCache(key, value, -1L);
    }

    public void saveCache(String key, Object value, long duration) {
        SharedPreferences.Editor edit = mSharedPreferences.edit();
        String valueStr = mGson.toJson(value);
        // 保存一个有数据有时间的内容
        if (duration != -1) {
            duration += System.currentTimeMillis();
        }
        CacheWithDuration cacheWithDuration = new CacheWithDuration(duration, valueStr);
        String withDurationValue = mGson.toJson(cacheWithDuration);
        edit.putString(key, withDurationValue);
        edit.apply();
    }

    public void delCache(String key) {
        mSharedPreferences.edit().remove(key).apply();
    }

    public <T> T getValue(String key, Class<T> clazz) {
        String withDurationValue = mSharedPreferences.getString(key, null);
        if (withDurationValue == null) {
            return null;
        }
        CacheWithDuration cacheWithDuration = mGson.fromJson(withDurationValue, CacheWithDuration.class);
        // 对时间进行判断
        long duration = cacheWithDuration.getDuration();
        if (duration != -1 && duration - System.currentTimeMillis() <= 0) {
            // 过期
            return null;
        } else {
            // 没有过期
            String value = cacheWithDuration.getValue();
            return mGson.fromJson(value, clazz);
        }
    }

    public static JsonCacheUtil getInstance() {
        if (sJsonCacheUtil == null) {
            sJsonCacheUtil = new JsonCacheUtil();
        }
        return sJsonCacheUtil;
    }


}
